package com.diy.task.bus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.diy.task.bus.entity.QuestionContent;
import com.diy.task.bus.entity.TaskContent;
import com.diy.task.bus.mapper.QuestionContentMapper;
import com.diy.task.bus.mapper.TaskContentMapper;
import com.diy.task.bus.service.ITaskContentService;
import com.diy.task.common.utils.Constant;
import com.diy.task.common.utils.TaskStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 话题内容表 服务实现类
 * </p>
 *
 * @author nengjie
 * @since 2019-03-05
 */
@Service
public class TaskContentServiceImpl extends ServiceImpl<TaskContentMapper, TaskContent> implements ITaskContentService {

    @Autowired
    private TaskContentMapper taskContentMapper;

    @Autowired
    private QuestionContentMapper questionContentMapper;


    /**
     * 根据ID获取话题详情表
     * @param id
     * @return
     */
    @Override
    public TaskContent getDetail(String id) {
        TaskContent taskContent = taskContentMapper.selectById(id);
        if (taskContent != null) {
            List<QuestionContent> questionContentList = getQuestionContentList(id);
            taskContent.setQuestionContentList(questionContentList);
        }
        return taskContent;
    }



    /**
     * 添加话题内容
     *
     * @param taskContent
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTaskContent(TaskContent taskContent) {
        taskContent.setDeleted(Constant.ZERO.getCode());
        taskContentMapper.insert(taskContent);
        List<QuestionContent> questionContentList = taskContent.getQuestionContentList();
        if (questionContentList != null) {
            for (int i = 0,size =questionContentList.size();i<size;i++) {
                QuestionContent questionContent = questionContentList.get(i);
                questionContent.setTaskContentId(taskContent.getId());
                questionContent.setCreator(taskContent.getCreator());
                questionContent.setModifier(taskContent.getCreator());
                questionContent.setQuestionOrder(i);

                questionContentMapper.insert(questionContent);
            }
        }

    }

    /**
     * 更新话题内容,先改为了不支持删除的处理 todo 支持删除更新
     * @param taskContent
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTaskContent(TaskContent taskContent) {
        taskContentMapper.updateById(taskContent);
        TaskContent detail = this.getDetail(taskContent.getId());
//        List<String> collect = detail.getQuestionContentList()
//                                    .stream()
//                                    .map(QuestionContent::getId)
//                                    .collect(Collectors.toList());

        List<QuestionContent> questionContentList = taskContent.getQuestionContentList();
        for (QuestionContent questionContent : questionContentList) {
            questionContent.setTaskContentId(taskContent.getId());
            questionContent.setCreator(taskContent.getCreator());
            questionContent.setModifier(taskContent.getCreator());
            questionContent.setDeleted(Constant.ZERO.getCode());
            if(questionContent.getId() == null){
                questionContentMapper.insert(questionContent);
            }else {
                questionContentMapper.updateById(questionContent);
            }
//            if(collect.contains(questionContent.getId())){
//                questionContentMapper.updateById(questionContent);
//                collect.remove(questionContent.getId());
//            }
        }
//        questionContentMapper.deleteBatchIds(collect);
    }

    /**
     * 获取小程序端的分页数据
     * @param taskContent
     * @param page
     * @param limit
     * @return
     */
    @Override
    public IPage<TaskContent> getAppletsList(TaskContent taskContent, Long page, Long limit) {
        QueryWrapper<TaskContent> taskContentQueryWrapper = new QueryWrapper<>();
        taskContentQueryWrapper.eq("is_deleted", Constant.ZERO.getCode()).orderBy(true, false, "task_number");
        IPage<TaskContent> taskContentIPage = taskContentMapper.selectPage(new Page<>(page, limit), taskContentQueryWrapper);

        List<TaskContent> records = taskContentIPage.getRecords();
        for (TaskContent record : records) {
            String taskContentId = record.getId();
            LocalDateTime endDate = record.getEndDate();
            LocalDateTime beginDate = record.getBeginDate();
            LocalDateTime currentLocalDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());

            // 结束时间在当前时间之前
            if (endDate.isAfter(currentLocalDateTime)) {
                record.setStatus(TaskStatusEnum.OVER.getMsg());
                record.setStatusCode(TaskStatusEnum.OVER.getCode());
            }

            // 开始时间在结束时间之前，结束时间在当前时间之后
            if (beginDate.isBefore(currentLocalDateTime) && endDate.isAfter(currentLocalDateTime)) {
                record.setStatus(TaskStatusEnum.PROCESSING.getMsg());
                record.setStatusCode(TaskStatusEnum.PROCESSING.getCode());
            }

            // 开始时间在当前时间之后的
            if (beginDate.isAfter(currentLocalDateTime)) {
                record.setStatus(TaskStatusEnum.NOTSTART.getMsg());
                record.setStatusCode(TaskStatusEnum.NOTSTART.getCode());
            }

            List<QuestionContent> questionContents = getQuestionContentList(taskContentId);
            record.setQuestionContentList(questionContents);
        }
        return taskContentIPage;
    }

    /**
     * 根据话题内容表ID 获取未删除的话题的具体题目
     * @param id
     * @return
     */
    private List<QuestionContent> getQuestionContentList(String id) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("task_content_id", id);
        queryMap.put("is_deleted", Constant.ZERO.getCode());
        List<QuestionContent> questionContentList = questionContentMapper.selectByMap(queryMap);
        return questionContentList;
    }
}
